package org.example.neusoft.dao;

import org.example.neusoft.model.User;
import org.example.neusoft.util.JDBCUtils;

import java.sql.Connection;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.sql.SQLException;

public class UserDao {
    public User loginUser(User user){
        Connection connection = JDBCUtils.getConnection();
        String sql = "select * from users where username = ? and password = ?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            ps.setString(2,user.getPassword());

            rs = ps.executeQuery();
            while (rs.next()){
                User userReturn = new User();
                userReturn.setId(rs.getString("id"));
                userReturn.setUsername(rs.getString("username"));
                userReturn.setPassword(rs.getString("password"));
                userReturn.setEmail(rs.getString("email"));
                return userReturn;
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return null;
    }
    public boolean regUser(User user) {
        Connection connection = JDBCUtils.getConnection();
        String sql = "select count(*) as cnt from users where username = ?";
        PreparedStatement ps = null;
        ResultSet rs = null;
        try {
            ps = connection.prepareStatement(sql);
            ps.setString(1,user.getUsername());
            rs = ps.executeQuery();
            while (rs.next()){
                int count = rs.getInt("cnt");
                if(count == 0){
                    String sqlInsert = "insert into users values(?,?,?,?)";
                    ps = connection.prepareStatement(sqlInsert);
                    ps.setString(1,user.getId());
                    ps.setString(2,user.getUsername());
                    ps.setString(3,user.getPassword());
                    ps.setString(4,user.getEmail());
                    int effected_rows = ps.executeUpdate();
                    return effected_rows == 1 ? true : false;
                }
                else{
                    return false;
                }
            }
        } catch (SQLException e) {
            throw new RuntimeException(e);
        }
        finally {
            try {
                rs.close();
                ps.close();
            } catch (SQLException e) {
                throw new RuntimeException(e);
            }
        }
        return false;
    }
}
